package com.top10.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.top10.bean.JwtUtil;
import com.top10.bean.PageBean;
import com.top10.bean.ResponseBean;
import com.top10.entity.Goods;
import com.top10.entity.UserBrowse;
import com.top10.entity.vo.BrowseVo;
import com.top10.service.IGoodsService;
import com.top10.service.IUserBrowseService;
import com.top10.service.IUserService;
import com.top10.utils.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 浏览记录Controller
 *
 * @author ellen
 * @version 1.0
 * @date 2018/11/23
 */
@RestController
@RequestMapping("/browse")
public class BrowseController {

	@Autowired
	IUserBrowseService userBrowseService;
	@Autowired
	IUserService userService;
	@Autowired
	IGoodsService goodsService;

	/**
	 * 添加浏览记录
	 *
	 * @param userBrowse
	 * @param request
	 * @return
	 */
	@RequestMapping("/manager/add")
	public ResponseBean add(UserBrowse userBrowse, HttpServletRequest request) {
		if (userBrowse.getTargetUuid() == null || userBrowse.getTargetUuid().trim().equals("")) {
			return ResponseBean.createError("目标商品uuid不能为空");
		}

		Goods goods = goodsService.selectOne(new EntityWrapper<Goods>().eq("uuid", userBrowse.getTargetUuid()));
		if(goods == null){
			return ResponseBean.createError("找不到该商品");
		}

		String userUuid = JwtUtil.getUuidByToken(request);
		UserBrowse originUserBrowse = userBrowseService.selectOne(new EntityWrapper<UserBrowse>().eq("user_uuid", userUuid).eq("target_uuid", userBrowse.getTargetUuid()));
		if(originUserBrowse != null){
			originUserBrowse.setCreatetime(new Date());
			userBrowseService.updateById(originUserBrowse);
			return ResponseBean.createSuccess().addData("userBrowse", originUserBrowse);
		}

		userBrowse.setUuid(RandomUtils.makeUUID());
		userBrowse.setUserUuid(userUuid);
		userBrowse.setIsdeleted(false);
		userBrowse.setCreatetime(new Date());
//        userBrowse.setUpdatetime(new Date());
		userBrowse.setCreator(userUuid);
		userBrowseService.insert(userBrowse);

		return ResponseBean.createSuccess().addData("userBrowse", userBrowse);
	}

	/**
	 * 用户浏览记录
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/manager/userBrowse")
	public ResponseBean userBrowse(HttpServletRequest request, PageBean pageBean) {
		String userUuid = JwtUtil.getUuidByToken(request);
		Page page = PageHelper.startPage(pageBean.getPageNum(), pageBean.getPageSize());
		List<BrowseVo> goodsList = userService.userBrowse(userUuid);
		pageBean = new PageBean(page.getPageNum(), page.getPageSize(), (int) page.getTotal());

		return ResponseBean.createSuccess().addData("goodsList", goodsList).addData("pageBean", pageBean);
	}

}